import type { AxiosRequestConfig, AxiosProgressEvent } from 'axios'
import type { LoadingInstance } from 'element-plus/es/components/loading/src/loading'
import type { ExportExcelPropsType } from './typings'
import { defineComponent, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  // ElDialog,
  // ElLink,
  ElLoading
} from 'element-plus'
import styles from './index.module.scss'

export default defineComponent({
  name: 'ExportExcel',
  props: ['visible', 'dispatchType', 'columns', 'payload', 'exportNumber'],
  emits: ['cancel'],
  setup(props: ExportExcelPropsType, { emit }) {
    const store = useStore()
    const progressRef = ref<number>(0)
    const loadRef = ref<LoadingInstance>()

    // 设置进度条回调
    const handleDownloadProgress: AxiosRequestConfig['onDownloadProgress'] = (
      progressEvent: AxiosProgressEvent
    ) => {
      // 代码中解释了为什么total为0的问题 ： 下载接口的response中没有Content-Length这个字段，后端接口返回一下就好了，里面存放的是文件的大小
      if (progressEvent.total !== 0) {
        const load = progressEvent.loaded
        const total = progressEvent.total || 1
        progressRef.value = (load / total) * 100
      }
    }

    onMounted(async () => {
      const { dispatchType, payload } = props
      loadRef.value = ElLoading.service({
        target: `.${styles['export-data-content']}`,
        text: '加载中'
      })
      if (dispatchType && payload) {
        await store
          .dispatch(
            dispatchType,
            Object.assign(
              {
                ...payload,
                params: {
                  ...(payload.params || {}),
                  titles: props.columns!.map((item) => item.prop)?.join?.(',')
                }
              },
              { onDownloadProgress: handleDownloadProgress }
            )
          )
          .then(async (res) => {
            if (res) emit('cancel')
          })
        loadRef.value!.close()
      }
    })

    // return () => (
    //   <ElDialog title="导出数据" modelValue={props.visible} beforeClose={() => emit('cancel')}>
    //     {/* <ElProgress textInside strokeWidth={24} percentage={progressRef.value} /> */}
    //     <ElLink class={styles['export-data-content']} underline={false} type="info">
    //       批量导出
    //       {props.exportNumber && (
    //         <>
    //           <span class={styles['export-data-total-number']}>{props.exportNumber}</span>条
    //         </>
    //       )}
    //       数据，正在生成导出文件！
    //     </ElLink>
    //   </ElDialog>
    // )
  }
})
